using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SkeleBatttleState : SkeleEnemyState
{
    Transform player;
    int moveDir;
    float dist;
    bool filpped;

    public SkeleBatttleState(SkeleEnemy skele, StateMachine stateMachine, string animName) : base(skele, stateMachine, animName)
    {
    }

    public override void Enter()
    {
        base.Enter();
        player = PlayerManager.Instance.Player.transform;
        stateTimer = skele.battleTime;
        filpped = false;
    }

    public override void Exit()
    {
        base.Exit();
    }

    public override void Update()
    {
        base.Update();

        if (player.GetComponent<PlayerData>().isDead)
            stateMachine.ChangeState(skele.idleState);

        if (player.position.x > skele.transform.position.x)
        {
            moveDir = 1;
        }
        else if (player.position.x < skele.transform.position.x)
        {
            moveDir = -1;
        }

        dist = Vector3.Distance(player.transform.position, skele.transform.position);

        if (dist < 0.8f)
        {
            skele.SetVelocity(skele.moveSpeed * skele.facingDir,skele.rb.velocity.y);
            return;
        }

        if (skele.IsPlayerDetected())
        {
            stateTimer = skele.battleTime;
            if (skele.IsPlayerDetected().distance < skele.attackDis)
            {
                if (CanAttack())
                    stateMachine.ChangeState(skele.attackState);
            }
        }
        else
        {
            if (filpped == false)
            {
                filpped = true;
                skele.FlipController(moveDir);
            }
            
            if (stateTimer < 0 || dist > 7)
                stateMachine.ChangeState(skele.idleState);

        }

        
                 
        

        skele.SetVelocity(moveDir * skele.moveSpeed * 1.2F, skele.rb.velocity.y);



    }

    bool CanAttack()
    {
        if(Time.time - skele.lastTimeAttacked > skele.attackCoolDown)
        {
            skele.lastTimeAttacked = Time.time;
            return true;
        }
        
        return false;
    }
}
